﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AioNightly.Model;
using MySql.Data.MySqlClient;
using AioNightly.Common;

namespace AioNightly.Dao
{
    public class CommentDAO
    {
        private void Read2List(MySqlDataReader reader, List<Comment> list)
        {
            while (reader.Read())
            {
                Comment it = new Comment();
                it.Id = reader.GetInt32(0);
                it.ItemId = reader.GetInt32(1);
                it.Content = reader.GetString(2);
                it.AuthorId = reader.GetInt32(3);
                it.CreateTime = reader.GetString(4);

                list.Add(it);
            }
        }

        public List<Comment> GetCommentByItemId(int itemId)
        {
            DBConnect db = new DBConnect();
            db.OpenConnection();

            List<Comment> list = new List<Comment>();
            string sql = string.Format("select * from comment where ItemId={0}", itemId);
            MySqlCommand cmd = new MySqlCommand(sql, db.Conn);
            MySqlDataReader reader = cmd.ExecuteReader();

            Read2List(reader, list);

            if (reader != null)
                reader.Close();

            db.CloseConnection();

            return list;
        }

        public int AddComment(int itemid, string comment, int authorid)
        {
            DBConnect db = new DBConnect();
            db.OpenConnection();

            string sql = string.Format("insert into comment (ItemId,Content,AuthorId,CreateTIme) values ({0},'{1}',{2},'{3}')", itemid, comment, authorid, TimeManager.GetSystemTime());
            MySqlCommand cmd = new MySqlCommand(sql, db.Conn);
            int result = cmd.ExecuteNonQuery();

            return result;
        }
    }
}